package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Api(tags = "菜品相关接口")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("/list")
    @Cacheable(value = "dish",key = "#categoryId+':'+#status")
    public R<List<DishDto>> queryDishByCategoryId(Long categoryId,Integer status){
        /*
          根据categoryId查询菜品集合数据：
          select * from dish where category_id = ? and status=?
          业务层使用：dishService来进行操作
         */
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(Dish::getCategoryId,categoryId);
        qw.eq(Dish::getStatus,status);
        List<Dish> list = dishService.list(qw);
        // List<Dish>   ---> List<DishDto>
        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dish : list) {
            DishDto dishDto = new DishDto();
            // 菜品的数据
            BeanUtils.copyProperties(dish,dishDto);
            // 口味数据 select * from dish_flavor where dish_id = ?
            LambdaQueryWrapper<DishFlavor> qw1 = new LambdaQueryWrapper<>();
            qw1.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> list1 = dishFlavorService.list(qw1);
            dishDto.setFlavors(list1);
            dishDtoList.add(dishDto);
        }
        return R.success(dishDtoList);
    }


    //清除
    @CacheEvict(value = "dish",allEntries = true)
    @PutMapping
    public R<String> upadteDish(@RequestBody DishDto dishDto){
        dishService.updateDishAndFlavor(dishDto);
        return R.success("修改成功！");
    }

    //清除
    @PostMapping
    @CacheEvict(value = "dish",key = "#dishDto.categoryId+':'+#dishDto.status")
    public R<String> saveDish(@RequestBody DishDto dishDto){
        //保存菜品和口味
        dishService.saveDishAndFlavor(dishDto);
        return R.success("保存成功");
    }


    @Autowired
    private CategoryService categoryService;

    //清除  怎么删除所有？？
    @CacheEvict(value = "dish",allEntries = true)
    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable Integer status,
                          @RequestParam List<Long> ids){
        //TODO update dish set status = 前端给我啥就是啥，错了找前端
        return R.success("操作成功");
    }

    //清除
    @DeleteMapping
    @CacheEvict(value = "dish",allEntries = true)
    public R deleteDish(@RequestParam List<Long> ids){
        System.out.println(ids);
        // TODO 完成业务逻辑
        return R.success("删除成功");
    }


    @GetMapping("/{id}")
    public R<DishDto> queryDishById(@PathVariable  Long id  ){
        DishDto dishDto = dishService.queryDishById(id);
        return R.success(dishDto);
    }


    @GetMapping("/page")
    public R queryPage(int page,int pageSize,String name){
        // 封装分页查询参数
        IPage<Dish> pageInfo = new Page<>(page,pageSize);

        // 条件查询 where name like '%xx%'
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        // name有可能不存在
        qw.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        dishService.page(pageInfo,qw);
        Map map = new HashMap();
        List<Dish> records = pageInfo.getRecords();
        // List<Dish> Dish中没有 categoryName
        List<DishDto> list = new ArrayList<>();
        for (Dish dish : records) {
            Long categoryId = dish.getCategoryId();
            //根据分类id查询分类数据
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(categoryName);
            BeanUtils.copyProperties(dish,dishDto);
            list.add(dishDto);
        }

        long total = pageInfo.getTotal();
        map.put("records",list);
        map.put("total",total);
        return R.success(map);
    }
}
